package com.ruoyi.doc.util;

import java.io.File;
import java.util.Map;
import java.util.UUID;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jdoper.util.JDoper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.doc.domain.SysDoc;
import com.ruoyi.doc.service.ISysDocService;

@Service
public class RyDocUtil {

    @Autowired
    private ISysDocService sysDocService;
    
    private static RyDocUtil docUtil;
    
    @PostConstruct
    public void init() {
    	docUtil = this;
    }

	/**
	 * 预览pdf文件-路径
	 * @param docXmlStr
	 * @return
	 * @throws Exception
	 */
	public static String getPdfPath(String docXmlStr) throws Exception {

		String fileName = encodingFilename();
		String filePath = RuoYiConfig.getDownloadPath();
		JDoper.convertXmlToPdfPath(docXmlStr, filePath, fileName);
		String fileNameEx = fileName + ".pdf";
        return fileNameEx;
	}
	
	/**
	 * 预览pdf文件-文件
	 * @param docXmlStr
	 * @return
	 * @throws Exception
	 */
	public static File getPdfFile(String docXmlStr) throws Exception {

		String fileName = encodingFilename();
		String filePath = RuoYiConfig.getDownloadPath();
        return JDoper.convertXmlToPdfFile(docXmlStr, filePath, fileName);
	}

    /**
     * 
     * @param docCode
     * @param fileType
     * @param fileName 如果为空，则自动生成文件名
     * @throws Exception 
     */
	public static String getDocFileName(String docCode, String fileType, String fileName, Map<String,Object> dataMap) throws Exception {

		if(StringUtils.isEmpty(fileType)) {
			throw new Exception("获取文档类型不能为空");
		} else if(!(fileType.equalsIgnoreCase("docx") ||fileType.equalsIgnoreCase("doc") ||fileType.equalsIgnoreCase("pdf"))) {
			throw new Exception("不支持的文档类型：" + fileType);
		}
		
		SysDoc doc = docUtil.sysDocService.selectSysDocByCode(docCode);
		if(StringUtils.isEmpty(fileName)) {
			fileName = encodingFilename();
		}
		String filePath = RuoYiConfig.getDownloadPath();
		
		JDoper.generatDocFile(doc.getDocxml(), dataMap, filePath, fileName);

		String fileNameEx = fileName + "." + fileType;
        return fileNameEx;
	}
    

    /**
     * 编码文件名
     */
    public static String encodingFilename()
    {
        return UUID.randomUUID().toString();
    }

}
